package sunyu.quartz.common.job;

import com.jfinal.kit.PropKit;
import org.nutz.lang.Stopwatch;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import sunyu.kit.common.LogKit;

/**
 * 一个job示例，这里还可以获取到spring上下文
 *
 * @author 孙宇
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution//这句话的目的是禁止相同描述的任务并发执行(避免上一个A任务未执行完，下一个A任务就开始了)
public class DemoJob extends QuartzJobBean {

    private static final String applicationContextSchedulerContextKey = PropKit.use("config-quartz.properties").get("quartz.applicationContextSchedulerContextKey");
    private static final Logger logger = LogKit.getLogger();
    private ApplicationContext applicationContext = null;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        Stopwatch sw = Stopwatch.begin();
        logger.info("示例任务开始");
        try {
            Thread.sleep(5000);//测试用，模拟这个任务要执行5秒钟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            //如果不使用spring可以不写这句话
            applicationContext = (ApplicationContext) context.getScheduler().getContext().get(applicationContextSchedulerContextKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        //logger.info("{}", applicationContext.getBean("dataSource"));
        sw.stop();
        logger.info("示例任务结束");
        logger.info(sw.toString());
    }
}
